package com.tr.ssocms.shiro;


import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @description: 自定义验证realm的方法  重写源码中
 *
 * @return {@link null}
 * @author  wangxihao
 * @email wangxh0108@163.com
**/
public class CustomModularRealmAuthenticator extends ModularRealmAuthenticator {



    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {

        //断言判断是否存在realm
        this.assertRealmsConfigured();
        //向下转型 authenticationToken转为自定义的
        CustomUsernamePasspordToken customUsernamePasspordToken = (CustomUsernamePasspordToken) authenticationToken;
        //得到登录类型  admin tiger LoginType.USER("user")
        String loginType = customUsernamePasspordToken.getLoginType();
        //得到真正配置的Realm并判断 （UserRealm MemberRealm）
        Collection<Realm> realms = this.getRealms();
        //定义Realm集合
        ArrayList<Realm> customRealm = new ArrayList();
        //遍历Realm
        for (Realm realm : realms) {
            //判断当前Realm名称中是否包含User or Member
            if(realm.getName().toLowerCase().contains(loginType.toLowerCase())){
                customRealm.add(realm);
            }
        }
        //有一个Realm的话 将当前realms.iterator().next()传入   多个的话 将  realms集合传入
        return realms.size() == 1 ? this.doSingleRealmAuthentication(realms.iterator().next(), customUsernamePasspordToken) : this.doMultiRealmAuthentication(realms, customUsernamePasspordToken);
    }
}
